<!--
 * @Author: Mcc
 * @Date: 2024-08-02 10:26:20
 * @LastEditors: 王明明834578987 10266004+wang-mingming-834578987@user.noreply.gitee.com
 * @LastEditTime: 2024-10-30 17:19:09
 * @FilePath: \ft-apply-admin\src\views\TrainList\components\Modal.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by Mcc, All Rights Reserved. 
-->
<template>
  <BasicModal v-bind="$attrs" :title="getTitle" @register="registerModal" @ok="handleSubmit">
    <BasicForm @register="registerForm"></BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { DatePicker, RangePicker, message } from 'ant-design-vue';
import { computed, defineComponent, ref, watch } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { addTrain } from './modal';
import { BasicForm, useForm } from '@/components/Form';
import { saveTrainingNumber, updateTrainingNumber, selectTrainingNumberDetail } from '@/api/applay/trainlist/self'
import dayjs from 'dayjs';
import { a } from './modal'
const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
  labelWidth: 130,
  baseColProps: { span: 24 },
  schemas: addTrain,
  showActionButtonGroup: false,
});
watch(a, (val) => {
  if (val&&treeData.value == 0 ) {
    const threeDay = new Date(getFutureDateWithTime(val)).getTime()
    setFieldsValue({ resultNoticeTime: formatTimestamp(threeDay) })
  }
})

function getFutureDateWithTime(dateString) {
  const date = new Date(dateString);
  // 加3天
  date.setDate(date.getDate() + 3);
  // 设置时间为下午1点
  date.setHours(13, 0, 0, 0); // 1 PM
  return date;
}

function formatTimestamp(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}
const treeData = ref();
const isUpdate = ref(true);
const getTitle = computed(() =>
  treeData.value == 0 ? '新增培训' : '编辑培训',
);
const trainingNumberId = ref()
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  console.log(data)
  treeData.value = data?.nums;
  resetFields()
  setModalProps({ confirmLoading: false })
  const { trainingNumberId: id } = data.value
  if (trainingNumberId) {
    trainingNumberId.value = id
    const res = await selectTrainingNumberDetail({ trainingNumberId: id })
    console.log(res)
    if (!res.code) {
      setFieldsValue({
        ...res,
        trainingUserIds: assignmentFun(res.trainingUserName),
        teacherUserIds: assignmentFun(res.trainingTeacherName),
      })
    }
  }
});

function assignmentFun(data) {
  if (data?.length) {
    return [...new Set(data)]
  } else {
    return []
  }
}

// 获取当前日期
const currentDate = dayjs();
// 获取两年后的日期
const twoYearsLater = dayjs().add(2, 'years');
const disabledDate = (current) => {
  if (!current) {
    return false;
  }
  // 禁用日期范围不在当前日期和两年后之间的日期
  return current.isBefore(currentDate, 'day') || current.isAfter(twoYearsLater, 'day');
}

const emit = defineEmits(['success', 'register']);
async function handleSubmit() {
  const values = await validate();
  setModalProps({ confirmLoading: true });
  try {
    let params = {
      ...values,
    }
    let fun = saveTrainingNumber
    // 编辑
    if (trainingNumberId.value) {
      fun = updateTrainingNumber
      params.trainingNumberId = trainingNumberId.value
    }
    const res = await fun(params)
    if (res?.code && res.code != '10000') {
      message.error(res.msg)
    } else {
      emit('success', params)
    }
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
<style lang='less' scoped>
:deep(.ant-modal) {
  width: 550px !important;
}

:deep(.ant-picker) {
  width: 100%;
}
</style>